package com.taotao.web.service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.taotao.common.service.ApiService;
import com.taotao.common.service.RedisService;
import com.taotao.manage.pojo.ItemDesc;
import com.taotao.manage.pojo.ItemParam;
import com.taotao.manage.pojo.ItemParamItem;
import com.taotao.web.bean.Item;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
public class ItemService {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    public static final String REDIS_KEY = "TAOTAO_WEB_ITEM_DELTAL"; //商品详情
    public static final String REDIS_DESC_KEY = "TAOTAO_WEB_ITEM_DESC"; //商品描述
    public static final String REDIS_PARAM_KEY = "TAOTAO_WEB_ITEM_PARAM"; //商品参数规格
    private static final Integer REDIS_TIME = 60 * 60 * 24; //缓存时间

    //注入ApiService
    @Autowired
    private ApiService apiService;
 
    //注入缓存service
    @Autowired
    private RedisService redisService;
    @Value("${TAOTAO_MANAGE_URL}")
    private String TAOTAO_MANAGE_URL;

    /**
     * 根据商品ID查询商品详情
     * @param itemId
     * @return
     */
    public Item getItemByItemId(Long itemId) {
        //从缓存中命中，如果命中中返回 
        String key = REDIS_KEY + itemId;

        try {
            String cacheData = this.redisService.get(key);

            if (StringUtils.isNotEmpty(cacheData)) {
                //命中直接返回
                return MAPPER.readValue(cacheData, Item.class);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String url = TAOTAO_MANAGE_URL + "/rest/item/" + itemId;

        try {
            String jsonData = apiService.doGet(url);

            if (StringUtils.isEmpty(jsonData)) {
                return null;
            }

            try {
                //未命中加入缓存
                this.redisService.set(key, jsonData, REDIS_TIME);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //反序列化
            return MAPPER.readValue(jsonData, Item.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据商品Id查询商品描述
     * @param itemId
     * @return
     */
    public ItemDesc queryDescByItemId(Long itemId) {
        //先查询缓存，命中则直接返回
        String key = REDIS_DESC_KEY + itemId;

        try {
            String cacheData = this.redisService.get(key);

            if (StringUtils.isNotEmpty(cacheData)) {
                //命中直接返回
                return MAPPER.readValue(cacheData, ItemDesc.class);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        String url = TAOTAO_MANAGE_URL + "/rest/item/desc/" + itemId;

        try {
            String jsonData = apiService.doGet(url);

            if (StringUtils.isEmpty(jsonData)) {
                return null;
            }

            try {
                //未命中将数据存储到缓存中
                this.redisService.set(key, jsonData, REDIS_TIME);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //反序列化
            return MAPPER.readValue(jsonData, ItemDesc.class);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据商品ID查询商品规格参数
     * @param itemId
     * @return
     */
    public String queryItemParamByItemId(Long itemId) {
        String key = REDIS_PARAM_KEY + itemId;

        try {
            //先从缓存中查询
            String cacheData = this.redisService.get(key);

            if (StringUtils.isNotEmpty(cacheData)) {
                //命中直接返回
                return cacheData;
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String url = TAOTAO_MANAGE_URL + "/rest/item/param/item/" + itemId;

        try {
            String jsonData = apiService.doGet(url);

            if (StringUtils.isEmpty(jsonData)) {
                return null;
            }

            //反序列化
            ItemParamItem itemParamItem = MAPPER.readValue(jsonData,
                    ItemParamItem.class);
            String paramData = itemParamItem.getParamData();

            //解析
            ArrayNode arrayNode = (ArrayNode) MAPPER.readTree(paramData);
            StringBuilder sb = new StringBuilder();
            sb.append(
                "<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"0\" class=\"Ptable\"><tbody>");

            for (JsonNode param : arrayNode) {
                sb.append("<tr><th class=\"tdTitle\" colspan=\"2\">" +
                    param.get("group").asText() + "</th></tr>");

                ArrayNode params = (ArrayNode) param.get("params");

                for (JsonNode p : params) {
                    sb.append("<tr><td class=\"tdTitle\">" +
                        p.get("k").asText() + "</td><td>" +
                        p.get("v").asText() + "</td></tr>");
                }
            }

            sb.append("</tbody></table>");

            try {
                //将数据加入到缓存中
                this.redisService.set(key, sb.toString(), REDIS_TIME);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return sb.toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}
